package com.flowcanto.gs1demo.server;

/** 
 * Implements the java.xml.namespace.NamespaceContext.
 * This allow XPaths over documents with namespaces in it.
 * 
 * For example if you want to match the id in:
 * <code><root><cat:id></code>
 * "/root/cat:id[0]" won't work in java.
 * With this class as context "/root/id[0]" will work. I'd still rather use 
 * "/root/cat:id", but that is still not possible. 
 * Sux to be me. 
 * 
 * @author Hampei
 */
import java.util.HashMap;
import java.util.Iterator;
import javax.xml.namespace.NamespaceContext;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

public class NamespaceContextImpl implements NamespaceContext {
	HashMap prefix2uri;
	HashMap uri2prefix;
	/** 
	 * Create a NamespaceContext for all namespaces declared in the NodeMap.
	 * @param atts most often document.getFirstChild().getAttributes(); 
	 */
	public NamespaceContextImpl(NamedNodeMap atts){
		prefix2uri = new HashMap();
		uri2prefix = new HashMap();
		for (int i=0;i < atts.getLength(); i++){
			Node n = atts.item(i);
			if (n.getNodeName().startsWith("xmlns:")){
				prefix2uri.put(n.getNodeName().substring(6), n.getNodeValue());
				uri2prefix.put(n.getNodeValue(), n.getNodeName().substring(6));
			}
		}				
	}
	/** Create a NameSpaceContext for 1 namespace with given 
	 * prefix and uri. 
	 */
	public NamespaceContextImpl(String prefix, String uri){
		prefix2uri = new HashMap();
		uri2prefix = new HashMap();
		prefix2uri.put(prefix, uri);
		uri2prefix.put(uri,prefix);
	}
	public String getNamespaceURI(String prefix){
		return (String) prefix2uri.get(prefix); 
	}
	
	public String getPrefix(String uri){
		return (String) uri2prefix.get(uri); 
	}
	public Iterator getPrefixes(String uri){
		return prefix2uri.keySet().iterator(); 
	}
}